package team.unstudio.unknownrpg_base.attribute;

import java.util.HashMap;
import java.util.Map;

import indi.defoliation.unknownrpg.api.attribute.Attribute;
import indi.defoliation.unknownrpg.api.attribute.AttributeBody;
import indi.defoliation.unknownrpg.api.attribute.AttributeEventHandler;
import indi.defoliation.unknownrpg.api.attribute.NumberAttribute;
import indi.defoliation.unknownrpg.api.rpgevent.entity.EntityAttackEvent;
import indi.defoliation.unknownrpg.api.RPGItemHelper;

public class DefenseAttribute extends Attribute implements NumberAttribute<Double>{

	private double defense=0;
	
	private final static String LETTER_KEY = "BlockChance";
	
	public DefenseAttribute(double defense) {
		this.set(defense);
	}
	
	public Map<String, Object> serialize() {
		HashMap<String,Object> map = new HashMap<>();
		map.put("defense", defense);
		return null;
	}

	@Override
	public void add(Double t) {
		this.defense+=t;
	}

	@Override
	public Double get() {
		return defense;
	}

	@Override
	public void set(Double t) {		
		this.defense=t;
	}

	@Override
	public String getKeyName() {
		return "Defense";
	}

	@Override
	public String getDisplayName() {
		return "Defense";
	}

	@Override
	public void deserialize(Map<String, Object> map) {
		this.defense=(double)map.get("defense");
	}
	
	@Override
	public Attribute getAttribute() {
		return this;
	}
	
	@AttributeEventHandler()
	public void onAttack(EntityAttackEvent event,Map<AttributeBody,Attribute> map) {
		double defense = RPGItemHelper.getAllOfAttributeValueInBodyItems(map);
		double damage = event.getChangeDamage();
		damage =(damage < defense) ? 0.05 : damage-defense; 
		if(event.hasLetter(LETTER_KEY))
			damage = computeBlockDamage(defense,damage);
		event.setDamage(this, damage);
	}

	private double computeBlockDamage(double defense,double damage) {
		double value = Math.log10(defense+1)*5;
		if(value>=9)value=9;
		value/=10;
		return damage*=value;
	}
}
